//
//  GameLayer.m
//  ProjectLila
//
//  Created by Tedo on 7/5/10.
//  Copyright 2010 sushigames. All rights reserved.
//

#import "GameLayer.h"
#import "PlayerMenuScene.h"
#import "GameScene.h"

#import "Unit.h"
#import "PlayerUnit.h"
#import "EnemyUnit.h"

@implementation GameLayer

- (id) init
{
	if( (self=[super init] )) {
		self.isTouchEnabled = YES;
		
		CGSize size = [[CCDirector sharedDirector] winSize];
		
		PlayerUnit *playerUnit;
		NSUInteger numUnits = 4 + 1; 
		for ( NSUInteger i = 1; i < numUnits; i++ )
		{
			if (i == 2 || i == 3)
				playerUnit = [PlayerUnit unitFromId:@"playerUnit0"];
			else if ( i == 4 )
				playerUnit = [PlayerUnit unitFromId:@"playerUnit1"];
			else
				playerUnit = [PlayerUnit unitFromId:@"playerUnit2"];
			playerUnit.position = ccp( size.width /6, size.height/numUnits *i );
			[self addChild:playerUnit z:-playerUnit.position.y];
		}
		
		/*
		EnemyUnit *enemyUnit;
		numUnits = 2 + 1; 
		for ( NSUInteger i = 1; i < numUnits; i++ )
		{
			enemyUnit = [EnemyUnit unitFromId:@"enemyUnit0"];
			//			enemyUnit = [EnemyUnit spriteWithFile: @"ball.png"];
			enemyUnit.position = ccp( size.width + 100, size.height/numUnits *i);
			enemyUnit.scaleX = 0.4;
			enemyUnit.scaleY = 0.4;
			[self addChild:enemyUnit z:-enemyUnit.position.y];
		}
		 */
		
		// exit button
		[CCMenuItemFont setFontSize:24];
        [CCMenuItemFont setFontName:@"Verdana"];
        CCMenuItem *exit = [CCMenuItemFont itemFromString:@"Exit"
												   target:self
												 selector:@selector(exit:)];
        CCMenu *menu = [CCMenu menuWithItems:exit, nil];
		[menu setPosition:ccp( size.width/10, size.height/10 )];
		[self addChild:menu];
		
		// update methods
		[self schedule:@selector(updateEnemyAI:)];
		[self schedule:@selector(updateAttacks:)];
		[self schedule:@selector(updateMove:)];
	}
	
	return self;
}

- (void)updateMove:(ccTime)dt {
	NSArray* playerUnits = [PlayerUnit allUnits];
	for (int i = 0; i < playerUnits.count; i++) {
		PlayerUnit *unit = [playerUnits objectAtIndex:i];
		if (unit.desiredPosition.x != -1 && unit.desiredPosition.y != -1) {
			CGPoint distance = ccpSub([unit desiredPosition], [unit position]);
			if (ccpLength(distance) > 15.0) {
				CGPoint moveDir = ccpNormalize(distance);
				CGPoint new = ccpAdd( unit.position, ccpMult( moveDir, [unit moveSpeed] * dt ) );
				unit.position = new;
				
				CCNode *parent = [unit parent];
				[parent reorderChild:unit z:-unit.position.y];
			}
		}
	}
}

- (void)updateAttacks:(ccTime)dt {
	NSArray *allUnits = [Unit allUnitsNotDead];
	for (int i = 0; i < allUnits.count; i++) {
		Unit *unit = [allUnits objectAtIndex:i];
		if (unit.state == ATTACK) {
			unit.attackElapsed += dt *1000; // in milliseconds
			//Check if target is dead
			if ([[unit attackTarget] state] == DEAD) {
				[unit changeStateTo:IDLE];
			}
			if (unit.attackElapsed >= unit.attackSpeed) {
				// Attack
				Unit *target = [unit attackTarget];
				[target damaged:unit.attackDamage];
				
				unit.attackElapsed = 0.0;
			}
		}
	}
	
	[self updateUnitAttackStates:[PlayerUnit allUnitsNotDead] versus:[EnemyUnit allUnitsNotDead]];
	[self updateUnitAttackStates:[EnemyUnit allUnitsNotDead] versus:[PlayerUnit allUnitsNotDead]];
	
}

- (void)updateUnitAttackStates:(NSArray *)group1 versus:(NSArray *)group2 {
	NSArray* playerUnits = group1;
	NSArray* enemyUnits = group2;
	for (int i = 0; i < playerUnits.count; i++) {
		Unit *playerUnit = [playerUnits objectAtIndex:i];
		
		// check unit's combat status
		if (playerUnit.state == ATTACK) {
			if (ccpDistance([playerUnit position], [[playerUnit attackTarget] position]) > [playerUnit attackRange]) {
				[playerUnit changeStateTo:IDLE];
			}
		}
		else {
			
			if ([playerUnit attackType] == NORMAL) {
				for (int j = 0; j < enemyUnits.count; j++) {
					Unit *enemyUnit = [enemyUnits objectAtIndex:j];
					
					if (ccpDistance([playerUnit position], [enemyUnit position]) < [playerUnit attackRange]) {
						[playerUnit changeStateTo:ATTACK];
						playerUnit.attackTarget = enemyUnit;
					}
				}
			}
			else if ([playerUnit attackType] == HEAL) {
				for (int j = 0; j < playerUnits.count; j++) {
					Unit *allyUnit = [playerUnits objectAtIndex:j];
					
					if (playerUnit == allyUnit)
						continue;
					
					if (ccpDistance([playerUnit position], [allyUnit position]) < [playerUnit attackRange]) {
						[playerUnit changeStateTo:ATTACK];
						playerUnit.attackTarget = allyUnit;
					}
				}
			}
		}
	}
}

- (void)updateEnemyAI:(ccTime)dt {
	NSArray *enemyUnits = [EnemyUnit allUnitsNotDead];
	for (EnemyUnit *unit in enemyUnits) {
		switch ([unit state]) {
			case IDLE:
				unit.position = ccp([unit position].x - [unit moveSpeed] * dt, [unit position].y);
				if ([unit position].x <= -100) {
					CGSize size = [[CCDirector sharedDirector] winSize];
					unit.position = ccp(size.width + 100, [unit position].y); 
				}
				break;
			default:
				break;
		}
	}
}

- (void)draw {
	[super draw];
	[self drawHealthBars];
}

- (void)drawHealthBars {
	
	glLineWidth(5.0f);
	
	NSArray * allUnits = [Unit allUnitsNotDead];
	NSUInteger i, count = [allUnits count];
	for (i = 0; i < count; i++) {
		Unit * unit = (Unit *)[allUnits objectAtIndex:i];
		CGPoint offset = ccpAdd(unit.position, ccp(-100.0, 75.0));
		float health = unit.health / unit.maxHealth;
		float size = 100.0;
		CGPoint start = ccpSub(offset, ccp(-size/2, 0.0));
		CGPoint end = ccpAdd(start, ccp(size*health, 0.0));
		CGPoint endFull = ccpAdd(start, ccp(size, 0.0));
		glColor4f(1.0, 0.0, 0.0, 1.0);  
		ccDrawLine(start, endFull);  
		glColor4f(0.0, 1.0, 0.0, 1.0);  
		ccDrawLine(start, end);
	}
}

- (void)ccTouchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
	
	UITouch *touch;
	for ( touch in touches ) {
		CGPoint location = [touch locationInView: [touch view]];
		CGPoint convertedLocation = [[CCDirector sharedDirector] convertToGL:location];
		
		NSArray * allUnits = [PlayerUnit allUnitsNotDead];
		NSUInteger i, count = [allUnits count];
		for (i = 0; i < count; i++) {
			PlayerUnit * unit = (PlayerUnit *)[allUnits objectAtIndex:i];
			if (CGRectContainsPoint([unit boundingBox], convertedLocation)) {				
				unit.touch = touch;
				
				break;
			}
		}
		
		//		NSLog( @"Touch Began, timestamp %d", touch.timestamp );
	}
}
- (void)ccTouchesMoved:(NSSet *)touches withEvent:(UIEvent *)event {
	
	UITouch *touch; 
	for ( touch in touches ) {
		CGPoint location = [touch locationInView: [touch view]];
		CGPoint convertedLocation = [[CCDirector sharedDirector] convertToGL:location];
		
		NSArray * allUnits = [PlayerUnit allUnitsNotDead];
		NSUInteger i, count = [allUnits count];
		for (i = 0; i < count; i++) {
			PlayerUnit * unit = (PlayerUnit *)[allUnits objectAtIndex:i];
			if (touch == unit.touch) {
				unit.desiredPosition = convertedLocation;
				break;
			}
		}
		
		//		NSLog( @"Touch Moved, timestamp %d", touch.timestamp );
	}
}
- (void)ccTouchesEnded:(NSSet *)touches withEvent:(UIEvent *)event {
	
	UITouch *touch;
	for ( touch in touches) {
		NSArray * allUnits = [PlayerUnit allUnitsNotDead];
		NSUInteger i, count = [allUnits count];
		for (i = 0; i < count; i++) {
			PlayerUnit * unit = (PlayerUnit *)[allUnits objectAtIndex:i];
			if (touch == unit.touch) {
				unit.touch = nil;
				
				break;
			}
		}
		
		//		NSLog( @"Touch Ended" );
	}
}
- (void)ccTouchesCancelled:(NSSet *)touches withEvent:(UIEvent *)event{
	NSLog( @"Touch Cancelled" );
}

- (void)exit:(id)sender {
	[[CCDirector sharedDirector] replaceScene:[CCFadeTransition transitionWithDuration:0.5f scene:[PlayerMenuScene scene]]];
}

@end
